package com.chencl.cipher.service;

import com.alibaba.fastjson.JSON;
import com.chencl.cipher.annotation.aspect.De2EncryptAspect;
import com.chencl.cipher.config.log.LogAspect;
import com.chencl.cipher.config.log.OperationLog;
import com.chencl.cipher.config.log.OperationLogDetail;
import com.chencl.cipher.dao.OperationLogMapper;
import com.chencl.cipher.dto.OperationLogDTO;
import com.chencl.cipher.util.PageInfo;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: dynamic-datasource
 * @description:
 * @author: jiangshengli
 * @create: 2022-03-17 14:43
 */
@Service
public class OperationLogService {

    @Autowired
    private OperationLogMapper operationLogMapper;

    public int insertLog(OperationLog operationLog){
        return operationLogMapper.insert(operationLog);
    }

    public OperationLog saveOperationLog(int code,String ip ,Object res,String declaringTypeName,String signatureName,Object[] args,String msg){
        OperationLog operationLog = new OperationLog();
        operationLog.setIp(ip);
        if(code==1){
            operationLog.setReturnValue(msg);
        }else{
            try{
                operationLog.setReturnValue(JSON.toJSONString(res));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        operationLog.setId(UUID.randomUUID().toString());
        operationLog.setArgs(JSON.toJSONString(args));
        operationLog.setCreateTime(new Date());
        operationLog.setMethod(declaringTypeName + "." + signatureName);
        operationLog.setAppid(LogAspect.getPValue("appid",args));
        operationLog.setUserId("#{currentUserId}");
        operationLog.setUserName("#{currentUserName}");
        insertLog(operationLog);
        return operationLog;
    }

    public PageInfo getOperationLogPage(int pageNum, int pageSize){
        int num = (pageNum-1)*pageSize;
        List<OperationLogDTO> operationLogDTOList = operationLogMapper.queryOperationLogPage(num,pageSize);
        int count = operationLogMapper.pageCount();
        PageInfo pageInfo = new PageInfo();
        pageInfo.setRows(count);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageList(operationLogDTOList);
        int pages = count/pageSize;
        if(count % pageSize != 0){
            pages ++;
        }
        pageInfo.setPages(pages);
        return pageInfo;
    }
}
